package org.ibase4j.system.service;

import lombok.extern.slf4j.Slf4j;
import org.ibase4j.system.model.SysUser;
import org.ibase4j.jwt.security.JwtUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author jie
 * @date 2018-11-22
 */
@Service
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {

    @Resource
    private SysAuthorizeService sysAuthorizeService;
    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("enable", 1);
        params.put("account", username);
        List<?> list = sysUserService.queryList(params);
        if (list.size() == 1) {
            SysUser user = (SysUser)list.get(0);
            return create(user);
        } else {
            log.info("No user: {}", username);
            return null;
        }
    }

    public UserDetails create(SysUser user) {
        return new JwtUser(
                user.getId(),
                user.getAccount(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
                sysAuthorizeService.queryPermissionByUserId(user.getId()),//sysAuthorizeService.getRolesByUserId(user.getId()),
                user.getEnable() > 0,
                new Timestamp(user.getCreateTime().getTime()),
                user.getUpdateTime()
        );
    }
}
